﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Common
{
    /// <summary>
    /// 对字符串的一些操作封装
    /// </summary>
    public static class StringHelper
    {
        /// <summary>
        /// 比较不区分大小写比较2个字符串的
        /// </summary>
        /// <param name="strA">The STR A.</param>
        /// <param name="strB">The STR B.</param>
        /// <returns></returns>
        public static bool Compare(string strA, string strB)
        {
            if (string.Compare(strA, strB, true) == 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// Gets the min string.
        /// </summary>
        /// <param name="str">The STR.</param>
        /// <param name="length">The length.</param>
        /// <returns></returns>
        public static string GetMinString(string str, int length)
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }
            string subfix = "...";

            //length = length - subfix.Length;
            StringBuilder s = new StringBuilder();
            int tempLength = 0;
            foreach (char var in str)
            {

                if (var > 255)
                {
                    tempLength += 2;
                }
                else
                {
                    tempLength += 1;
                }
                if (tempLength > length)
                {
                    RemoveString(s, subfix);

                    break;
                }
                s.Append(var);
            }

            return s.ToString();

        }

        /// <summary>
        /// Removes the string.
        /// </summary>
        /// <param name="s">The s.</param>
        /// <param name="subfix">The subfix.</param>
        private static void RemoveString(StringBuilder s, string subfix)
        {
            int length = subfix.Length;
            int tempLength = 0;
            for (int i = 1; i <= length; i++)
            {
                char var = s[s.Length - i];
                if (var > 255)
                {
                    tempLength += 2;
                }
                else
                {
                    tempLength += 1;
                }
                s.Remove(s.Length - 1, 1);
                if (tempLength > length)
                {
                    s.Append(subfix);
                    break;
                }


            }

        }
    }
}
